import re
index = 'Merchant of Venice_ List of Scenes.html'
filename = 'Merchant of Venice_ List of Scenes_cp.md'
dic = {}  # 统计每个标签对应的数量


def get_tags(file):  # 对一个特定的文件统计其中的标签数
    f = open(file, 'r')
    content = f.read().lower()
    tags = re.findall(r'(?<=<)[a-z\d]+(?=.*>)', content)
    for i in tags:
        if i in dic:
            dic[i] += 1
        else:
            dic[i] = 1
    f.close()
    return


def get_href():  # 从第一个html中摘取所有链接
    get_tags(index)
    with open(index, 'r') as f:
        lines = f.read().lower()
        pat_href = re.compile(r'(?<=<a href=).*(?=>.+</a><br>)')
        line = pat_href.findall(lines)
        hrefs = []
        for i in line:
            hrefs.append(i.strip('"'))
        return hrefs


def put_acts():  # 不能让两个函数同时打开一个文件并操作*****找了半天才发现错在这里
    f = open(filename, 'w')  # 将所有文本组织起来
    f.write('\n# The Merchant of Venice\n\n')
    hrefs = get_href()
    f.close()
    for i in range(len(hrefs)):
        f = open(filename, 'a')
        if i == 0:
            f.write('## Act 1\n')
        if i == 3:
            f.write('## Act 2\n')
        if i == 12:
            f.write('## Act 3\n')
        if i == 17:
            f.write('## Act 4\n')
        if i == 19:
            f.write('## Act 5\n')
        f.close()
        get_scenes(hrefs[i])
        get_tags(hrefs[i])
    return


def get_scenes(line):  # 对一个特定的剧本网页写入其中的全部文本
    with open(line, 'r+') as f:
        words = f.read().lower()
        scene = re.findall(r'(?<=<h3>).+(?=</h3>)', words)
        enter = re.findall(r'(?<=<i>).+(?=</i>)', words)
        names1 = re.findall(r'(?<=<a name=speech\d).+?(?=</a>)', words)
        names = []
        for i in names1:
            str2 = re.findall(r'(?<=<b>).*?(?=</b>)', i)[0]
            names.append(str2)
        pat_quote = re.compile(r'(?<=<a name=speech\d)[\s\S]*?(?=</blockquote>)')
        quote = pat_quote.findall(words)
        ff = open(filename, 'a')
        ff.write('\n### '+scene[0].upper()+'\n\n')
        ff.write('*'+enter[0].title()+'*\n')
        for i in range(len(quote)):
            s_name = get_name(quote[i])
            ff.write('\n**'+names[i].upper()+'**\n\n')
            for j in s_name:
                ff.write(j.strip().capitalize()+'\n')
        ff.close()
    return


def get_name(quote_line):  # get_scenes的附属函数，解析出每个人的台词文本并返回一个列表
    pat_speech = re.compile(r'(?<=<a name=\d).*(?=/a>)')
    line1 = pat_speech.findall(quote_line)
    line2 = []
    for i in line1:
        str1 = re.findall(r'(?<=>).*?(?=<)', i)[0]
        line2.append(str1)
    return line2


def list_tags():  # 排序dic中的标签数并打印
    tup = dic.items()
    sort1 = sorted(tup, key=lambda x: x[1], reverse=True)
    for i in range(len(sort1)):
        print('第'+str(i+1)+'名:'+'<'+sort1[i][0]+'>标签出现了'+str(sort1[i][1])+'次；')
    return


if __name__ == '__main__':
    put_acts()
    list_tags()
    print('over!')
